package com.chencs.app.product.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chencs.app.AppCommon;
import com.chencs.app.product.mapper.AppProductMapper;
import com.chencs.biz.Common;
import com.chencs.biz.product.model.JuHuaSuanResponse;
import com.chencs.biz.product.model.SimilarProductResponse;
import com.chencs.biz.product.model.SimpleProductResponse;
import com.chencs.biz.product.model.TbkCouponResponse;
import com.chencs.coupon.CouponUtils;
import com.chencs.utils.*;
import com.chencs.vo.biz.config.JuHuaSuanModel;
import com.chencs.vo.biz.password.*;
import com.chencs.vo.biz.product.CmdModel;
import com.chencs.vo.biz.product.ProductModel;
import com.chencs.vo.biz.shop.ShopModel;
import com.chencs.vo.net.request.*;
import com.chencs.vo.net.response.*;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.*;
import com.taobao.api.response.*;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;

/**
 * Created by fangzehua on 2017/7/11.
 */
@Service
@Transactional
public class AppProductService {


    Random random = new Random();


    @Autowired
    private AppProductMapper appProductMapper;


    public SimpleProductResponse getSimpleProductByPid(String pid){
        SimpleProductResponse response =null;
        TaobaoClient client = new DefaultTaobaoClient(Common.apiUrl+Common.pro_item,Common.appKey,Common.appSecre);
        TbkItemInfoGetRequest req = new TbkItemInfoGetRequest();
        req.setFields("click_url,num_iid,title,pict_url,small_images,reserve_price,zk_final_price,user_type,provcity,item_url");
        req.setPlatform(2L);
        req.setNumIids(pid);
        TbkItemInfoGetResponse rsp = null;
        try {
            rsp = client.execute(req);
            response = new SimpleProductResponse();
            response.setnTbkItem(rsp.getResults().get(0));
            //  System.out.println(rsp.getBody());
            response.setModel(appProductMapper.findProductByPid(pid));
            return response;
        } catch (ApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }


    public ShopModel getShopInfo(String shopname){
        ShopModel shopModel = new ShopModel();
        TaobaoClient client = new DefaultTaobaoClient(Common.apiUrl+"taobao.tbk.shop.get", Common.appKey,Common.appSecre);
        TbkShopGetRequest req = new TbkShopGetRequest();
        req.setFields("user_id,shop_title,shop_type,seller_nick,pict_url,shop_url,is_tmall");
        req.setQ(shopname);
        req.setSort("commission_rate_des");
        req.setPageNo(1L);
        req.setPageSize(1L);
        TbkShopGetResponse rsp;
        try {
            rsp = client.execute(req);
            //System.out.println(rsp.getBody());
            if(rsp!=null){
                shopModel.setIcon(rsp.getResults().get(0).getPictUrl());
                shopModel.setName(rsp.getResults().get(0).getShopTitle());
                shopModel.setUrl(rsp.getResults().get(0).getShopUrl());
                shopModel.setType(rsp.getResults().get(0).getShopType().equals("B")?"1":"0");
                shopModel.setId(rsp.getResults().get(0).getUserId()+"");
            }
        } catch (ApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return  null;
        }
        return  shopModel;
    }

    public ProductListResponse searchProducts(ProductListRequest request){
        ProductListResponse response = new ProductListResponse();
        Map<String,Object> map = new HashMap<String,Object>();

        if (StringUtils.isNotBlank(request.getCid())){
            map.put("cid",request.getCid());
        }
        if (StringUtils.isNotBlank(request.getCpid())){
            map.put("cpid",request.getCpid());
        }
        if (StringUtils.isNotBlank(request.getKey())){
            map.put("pname","%"+request.getKey()+"%");
        }
        if (StringUtils.isNotBlank(request.getIsnew())){
            map.put("isnew",request.getIsnew());
        }
        if (StringUtils.isNotBlank(request.getFlag())){
            map.put("flag",request.getFlag());
        }
        if (StringUtils.isNotBlank(request.getKey())){
            map.put("key",request.getKey());
        }

        if (StringUtils.isNotBlank(request.getPrice())){
            map.put("price",request.getFlag());
        }
        if (StringUtils.isNotBlank(request.getHot())){
            map.put("hot",request.getHot());
        }
        if (StringUtils.isNotBlank(request.getCoupon())){
            map.put("coupon",request.getCoupon());
        }
        if (StringUtils.isNotBlank(request.getSales())){
            map.put("sales",request.getSales());
        }
        if (StringUtils.isNotBlank(request.getTime())){
            map.put("time",request.getTime());
        }

        map.put("pageno",request.getPageNo()*request.getPageSize());
        map.put("pagesize",request.getPageSize());
        //    System.out.print(map.toString());
        List<ProductModel> list = appProductMapper.searchProducts(map);
        response.setProducts(list);
        return  response;
    }


    public SimilarProductResponse searchSimilarProducts(Long pid){
        SimilarProductResponse response = new SimilarProductResponse();
        TaobaoClient client = new DefaultTaobaoClient(Common.apiUrl+"taobao.tbk.item.recommend.get",Common.appKey,Common.appSecre);
        TbkItemRecommendGetRequest req = new TbkItemRecommendGetRequest();
        req.setFields("num_iid,title,pict_url,reserve_price,zk_final_price,user_type,provcity,item_url");
        req.setNumIid(pid);
        req.setCount(20L);
        req.setPlatform(2L);
        TbkItemRecommendGetResponse rsp;
        try {
            rsp =  client.execute(req);
            if (rsp!=null){
                response.setnTbkItemList(rsp.getResults());
                return  response;
            }else{
                return null;
            }
        } catch (ApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return  null;
        }
    }


    public TbkCouponResponse getParityProductList(ProductRequest request){
        TbkCouponResponse response = new TbkCouponResponse();
        TaobaoClient client = new DefaultTaobaoClient(Common.apiUrl+"taobao.tbk.dg.item.coupon.get",Common.appKey,Common.appSecre);
        TbkDgItemCouponGetRequest req = new TbkDgItemCouponGetRequest();
        req.setPlatform(2L);
        req.setAdzoneId(Common.adzoneId);
        req.setPageSize(Long.parseLong(request.getPageSize()+""));
        req.setQ(request.getKey());
        req.setPageNo(Long.parseLong(request.getPageNo()+""));
        try {
            TbkDgItemCouponGetResponse rsp = null;
            rsp = client.execute(req);
            if(rsp.getResults()!=null){
                response.setResults(rsp.getResults());
            }else{
                return  null;
            }
        } catch (ApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
        return  response;
    }



    public ProductListResponse topList(PushRequest request){
        ProductListResponse response = new ProductListResponse();
        Map<String,Object> map = new HashMap<String,Object>();

        int s = random.nextInt(6) + 3;
        int page = request.getPageNo();
        if(page==0){
            map.put("pageno",s*request.getPageSize());
        }else{
            map.put("pageno",request.getPageNo()*request.getPageSize());
        }
        map.put("cid",request.getType());
        map.put("pagesize",request.getPageSize());
        //  System.out.print(map.toString());
        List<ProductModel> list = appProductMapper.topList(map);
        response.setProducts(list);
        return  response;
    }


    public ProductListResponse dayUpdate(PushRequest request){
        ProductListResponse response = new ProductListResponse();
        Map<String,Object> map = new HashMap<String,Object>();
        int s = random.nextInt(6) + 3;
        int page = request.getPageNo();
        if(page==0){
            map.put("pageno",s*request.getPageSize());
        }else{
            map.put("pageno",request.getPageNo()*request.getPageSize());
        }
        map.put("cid",request.getType());
        map.put("pagesize",request.getPageSize());
        // System.out.print(map.toString());
        List<ProductModel> list = appProductMapper.dayUpdate(map);
        response.setProducts(list);
        return  response;
    }


    /**
     * 聚划算
     * @param request
     * @return
     */
    public JuHuaSuanResponse juHuaSuan(ProductRequest request){
        JuHuaSuanResponse juHuaSuanResponse = new JuHuaSuanResponse();
        TaobaoClient client = new DefaultTaobaoClient(Common.apiUrl+"taobao.ju.items.search",Common.appKey,Common.appSecre);
        JuItemsSearchRequest req = new JuItemsSearchRequest();
        JuItemsSearchRequest.TopItemQuery obj1 = new JuItemsSearchRequest.TopItemQuery();
        obj1.setCurrentPage(Long.parseLong(request.getPageNo()+"")==0?1l:request.getPageNo());
        obj1.setPageSize(Long.parseLong(request.getPageSize()+""));
        obj1.setPid(Common.adzoneId+"");
        obj1.setPostage(true);
        obj1.setStatus(2L);
        obj1.setWord(request.getKey());
        req.setParamTopItemQuery(obj1);
        JuItemsSearchResponse rsp;
        try {
            rsp = client.execute(req);
            rsp.setBody("");
            rsp.setParams(null);
            juHuaSuanResponse.setList(rsp);
            return  juHuaSuanResponse;
        } catch (ApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }


    public JHSModelResponse getJhsItem(RequestBase requestBase){
        JHSModelResponse  response = new JHSModelResponse();
        List<JuHuaSuanModel> list = appProductMapper.getJhsItem(null);
        response.setList(list);
        return  response;
    }



    /***
     * 5月 16号新增接口
     * @param cmd
     * @return
     */

    public SimpleProductResponse getComdXXXXX(String cmd){
        SimpleProductResponse response = new SimpleProductResponse();
        ProductModel productModel =  CouponUtils.getCoupon(cmd);
        if(productModel!=null){
            response.setModel(productModel);
            return response;
        }else{
            return  null;
        }
    }


    /***
     * 5月 16号以前接口
     * @param cmd
     * @return
     */
    public SimpleProductResponse getComdX(String cmd){
        SimpleProductResponse response = new SimpleProductResponse();
        Map<String,String>  map2 =  TaoKouLingUtils.getTaoKouLing(cmd);

        try {
            QinTao qinTao2 = new QinTao();
            qinTao2.setInfo(map2.get("coupon_info")+"√");
            qinTao2.setPrice(com.chencs.utils.StringUtils.getCoupon(map2.get("coupon_info"))+"");
            qinTao2.setUrl(map2.get("click"));
            List<QinTao> qinTaoList = new ArrayList<>();
            ProductModel model = new ProductModel();
            model.setProimg(map2.get("img"));
            model.setPname(map2.get("title"));
            if(com.alibaba.druid.util.StringUtils.isEmpty(map2.get("price"))){
                model.setPrice(map2.get("coupon_info"));
            }else{
                model.setPrice(map2.get("price"));
            }
            model.setCounpurl(map2.get("click"));
            qinTaoList.add(qinTao2);
            model.setList(qinTaoList);
            model.setProurl(map2.get("click"));
            response.setModel(model);
        }catch (Exception e){
            return  null;
        }
        return  response;
    }





    /**
     * 慧万村接口
     * @param cmd
     * @return
     */
    public SimpleProductResponse getComd2(String cmd){

        String requestStr = "{\"content\":\""+cmd+"\"}";
        SimpleProductResponse response = new SimpleProductResponse();
        try{
            PostMethod getMethod = new PostMethod("https://api.huiwancun.net/HwcWxappService/taobaoapp/parseProduct.api");
            RequestEntity entity = new StringRequestEntity(requestStr,"application/json","UTF-8");
            getMethod.setRequestEntity(entity);
            getMethod.setRequestHeader("Content-Type","application/json;charset=UTF-8");
            new HttpClient().executeMethod(getMethod);
            InputStream inputStream = getMethod.getResponseBodyAsStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            StringBuffer stringBuffer = new StringBuffer();
            String str= "";
            while((str = br.readLine()) != null){
                stringBuffer .append(str);
            }
            String str2 = stringBuffer.toString();
            System.out.println(str2);
            Boolean flag  = JSONObject.parseObject(str2).getBoolean("success");

            if(flag){
                JSONObject base  = JSONObject.parseObject(str2).getJSONObject("product");
                JSONArray baseList = JSONArray.parseArray(base.getString("coupons"));
                List<QinTao> qinTaoList = new ArrayList<>();

                QinTao qinTaonull = new QinTao();
                qinTaoList.add(qinTaonull);
                //拿轻私有券的券
                String pid = base.getString("open_id");
                Map<String,String>  getSiyouquan = ApplyCommissionUtils.getSiyouquan(pid);

//                System.out.println(getSiyouquan.toString());
                if(getSiyouquan!=null){
                    if(!getSiyouquan.get("flag").equals("0")){ //没私有券
                        qinTaoList.clear();
                    }
                }else{
                    qinTaoList.clear();
                }

                QinTao qinTao =null;
                for(int i=0;i<baseList.size();i++){
                    qinTao = new QinTao();
                    String amount = baseList.getJSONObject(i).getString("amount");
                    qinTao.setInfo(baseList.getJSONObject(i).getString("applyAmountTxt"));
                    qinTao.setPrice(amount);
                    if(getSiyouquan!=null){
                        if(getSiyouquan.get("e")!=null){
                            qinTao.setUrl(com.chencs.utils.StringUtils.repcUrl(baseList.getJSONObject(i).getString("urlpath"),getSiyouquan.get("e")));
                        }else{
                            qinTao.setUrl(com.chencs.utils.StringUtils.repcUrl(baseList.getJSONObject(i).getString("urlpath")));
                        }
                    }else{
                        qinTao.setUrl(com.chencs.utils.StringUtils.repcUrl(baseList.getJSONObject(i).getString("urlpath")));
                    }

                    if(!qinTao.getUrl().equals("-1")){ //判断私有券
                        qinTaoList.add(qinTao);
                    }

                }


                ProductModel model = new ProductModel();


                if(getSiyouquan!=null){
                    if(getSiyouquan.get("flag").equals("0")){//有私有券
                        QinTao qinTao2 = new QinTao();
                        qinTao2.setInfo(getSiyouquan.get("coupon_info")+"√");
                        qinTao2.setPrice(getSiyouquan.get("price"));
                        qinTao2.setUrl(getSiyouquan.get("url"));
                        for(int i=1;i<qinTaoList.size();i++){
                            qinTaoList.get(i).setUrl(getSiyouquan.get("url")+"&e="+com.chencs.utils.StringUtils.repcUrl2(qinTaoList.get(i).getUrl()));
                        }
                        qinTaoList.set(0,qinTao2);
                        model.setProurl(getSiyouquan.get("click"));
                    }else{
                        model.setProurl(getSiyouquan.get("click"));
                        // model.setProurl(base.getString("urlpath"));
                    }
                }else{
                    // model.setProurl(getSiyouquan.get("click"));
                    model.setProurl(base.getString("urlpath"));
                }


                model.setProimg(base.getString("pic_url"));
                model.setPname(base.getString("title"));
                model.setPrice(base.getString("price"));
                model.setPid(base.getString("open_id"));
                model.setSellerid(base.getString("sellerid"));
                model.setCounpurl("http://h5.m.taobao.com/jxt/coupon-tb.html?sellerId="+model.getSellerid()+"&itemId="+model.getPid()+"");
                model.setList(qinTaoList);
                response.setModel(model);
            }  else{

                return  null;
            }

        }catch (Exception e){
            e.printStackTrace();
            response.setCode(0);
            return  response;
        }

        if(CollectionUtils.isEmpty(response.getModel().getList())){
            response.setCode(0);
        }
        return  response;
    }


    /**
     * 拿淘宝接口解析的
     * @param cmd
     * @return
     */
    public SimpleProductResponse getComd3(String cmd){


        SimpleProductResponse response = new SimpleProductResponse();
//        try{
//
//            TaoKouLing taoKouLing =  TaoKouLingUtils.getTaoKouLing(new String(decode(cmd))); //如果返回了口令
//            if(taoKouLing!=null){
//
//                Map<String, String>  map =   CRequest.URLRequest(taoKouLing.getUrl());
//
//                JSONObject base  = JSONObject.parseObject("").getJSONObject("product");
//                JSONArray baseList = JSONArray.parseArray(base.getString("coupons"));
//                List<QinTao> qinTaoList = new ArrayList<>();
//                QinTao qinTaonull = new QinTao();
//                qinTaoList.add(qinTaonull);
//                //拿轻私有券的券
//                String pid = base.getString("open_id");
//                Map<String,String>  getSiyouquan = ApplyCommissionUtils.getSiyouquan(pid);
//
////                System.out.println(getSiyouquan.toString());
//                if(getSiyouquan!=null){
//                    if(!getSiyouquan.get("flag").equals("0")){ //没私有券
//                        qinTaoList.clear();
//                    }
//                }else{
//                    qinTaoList.clear();
//                }
//
//                QinTao qinTao =null;
//                for(int i=0;i<baseList.size();i++){
//                    if (i>4){
//                        break;
//                    }
//                    qinTao = new QinTao();
//                    String amount = baseList.getJSONObject(i).getString("amount");
//                    qinTao.setInfo(baseList.getJSONObject(i).getString("applyAmountTxt"));
//                    qinTao.setPrice(amount);
//                    if(getSiyouquan!=null){
//                        if(getSiyouquan.get("e")!=null){
//                            qinTao.setUrl(com.chencs.utils.StringUtils.repcUrl(baseList.getJSONObject(i).getString("urlpath"),getSiyouquan.get("e")));
//                        }else{
//                            qinTao.setUrl(com.chencs.utils.StringUtils.repcUrl(baseList.getJSONObject(i).getString("urlpath")));
//                        }
//                    }else{
//                        qinTao.setUrl(com.chencs.utils.StringUtils.repcUrl(baseList.getJSONObject(i).getString("urlpath")));
//                    }
//
//
//
//                    if(!qinTao.getUrl().equals("-1")){ //判断私有券
//                        qinTaoList.add(qinTao);
//                    }
//
//                }
//
//
//                ProductModel model = new ProductModel();
//
//
//                if(getSiyouquan!=null){
//                    if(getSiyouquan.get("flag").equals("0")){//有私有券
//                        QinTao qinTao2 = new QinTao();
//                        qinTao2.setInfo(getSiyouquan.get("coupon_info")+"√");
//                        qinTao2.setPrice(getSiyouquan.get("price"));
//                        qinTao2.setUrl(getSiyouquan.get("url"));
//                        for(int i=1;i<qinTaoList.size();i++){
//                            qinTaoList.get(i).setUrl(getSiyouquan.get("url")+"&e="+com.chencs.utils.StringUtils.repcUrl2(qinTaoList.get(i).getUrl()));
//                        }
//                        qinTaoList.set(0,qinTao2);
//                        model.setProurl(getSiyouquan.get("click"));
//                    }else{
//                        model.setProurl(getSiyouquan.get("click"));
//                        // model.setProurl(base.getString("urlpath"));
//                    }
//                }else{
//                    // model.setProurl(getSiyouquan.get("click"));
//                    model.setProurl(base.getString("urlpath"));
//                }
//
//
//                model.setProimg(base.getString("pic_url"));
//                model.setPname(base.getString("title"));
//                model.setPrice(base.getString("price"));
//                model.setPid(base.getString("open_id"));
//                model.setSellerid(base.getString("sellerid"));
//                model.setCounpurl("http://h5.m.taobao.com/jxt/coupon-tb.html?sellerId="+model.getSellerid()+"&itemId="+model.getPid()+"");
//                model.setList(qinTaoList);
//                response.setModel(model);
//            }  else{
//
//                return  null;
//            }
//
//        }catch (Exception e){
//            e.printStackTrace();
//            response.setCode(0);
//            return  response;
//        }
//
//        if(CollectionUtils.isEmpty(response.getModel().getList())){
//            response.setCode(0);
//        }
        return  response;
    }







    /**
     * 反向解析淘口令
     * @param cmd
     * @return
     */
    public SimpleProductResponse getComd(String cmd){
        SimpleProductResponse response = new SimpleProductResponse();
        String str[] = cmd.split("￥");


        //  String cmdstr = HttpPostGiftCode.http("￥"+str[1]+"￥");
        //  CmdModel cmdModel = JSON.parseObject(cmdstr,CmdModel.class);

        String code = HttpPostGiftCode.http2("￥"+str[1]+"￥");
         System.out.println("----------------------"+code);
        JSONObject xbs  = JSONObject.parseObject(code);
        CmdModel cmdModel = JSON.parseObject(xbs.getString("data"),CmdModel.class);

        try {
            if(cmdModel!=null){
                if(cmdModel.getPicUrl().indexOf("http")>-1){
                    cmdModel.setContent(MoneyUtils.getCmd(cmdModel.getContent()));
                    ProductModel model = new ProductModel();
                    model.setProurl(cmdModel.getUrl());
                    model.setProimg(cmdModel.getPicUrl());
                    model.setPname(cmdModel.getContent());
                    Map<String, String> mapRequest = CRequest.URLRequest(cmdModel.getUrl());
                    model.setPrice(mapRequest.get("price"));
                    model.setPid(mapRequest.get("id"));
                    model.setCouponcode("0");
                    //  GetTmailUrl.getTaboSellerId("http://item.taobao.com/item.htm?id="+mapRequest.get("id"),model);
                    response.setModel(model);
                }else{
                    return null;
                }
            }else{
                return null;
            }
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
        return  response;
    }


    /**
     * 轻淘客
     * @return
     */
    public String getQuan(String str){
        String string =  HttpPostGiftCode.QingTaoKe("1702834696","543523129610");
        // System.out.println(string);
        return "";

    }
    /**
     * 选品大人
     * @return
     */
    public String getXPDR(String str){

        try {
            String string =  HttpPostGiftCode.XPDR(str);
            // System.out.println(string);
        }catch (Exception E){
            E.printStackTrace();
        }

        return "";

    }



    //天猫
    public SimpleProductResponse getTmallComd(ProductModel model){
        SimpleProductResponse response = new SimpleProductResponse();
        response.setModel(model);
        return  response;
    }




    public static byte[] decode(String str){
        byte[] bt = null;
        try {
            sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
            bt = decoder.decodeBuffer( str );
        } catch (IOException e) {
            e.printStackTrace();
        }

        return bt;
    }


    public   List<TbkDgItemCouponGetResponse.TbkCoupon>  getCouponByPname(String name) {
        TaobaoClient client = new DefaultTaobaoClient(Common.apiUrl + "taobao.tbk.dg.item.coupon.get", Common.appKey, Common.appSecre);
        List<TbkDgItemCouponGetResponse.TbkCoupon> list = null;
        TbkDgItemCouponGetRequest req = new TbkDgItemCouponGetRequest();
        req.setPlatform(2L);
        req.setAdzoneId(Common.adzoneId);
        req.setPageSize(30l);
        req.setQ(name);
        req.setPageNo(1l);
        try {
            TbkDgItemCouponGetResponse rsp = null;
            rsp = client.execute(req);
            if (rsp.getResults() != null) {
                list = rsp.getResults();
            } else {
                return null;
            }
        } catch (ApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
        return list;
    }



    //申请记录
    public void applyCommission(String post,ApplyCommission applyCommission){
        System.out.println( JSON.toJSONString(applyCommission));
        ApplyLog applyLog = new ApplyLog();
        applyLog.setFid(applyCommission.getFid());
        applyLog.setMid(applyCommission.getMid());
        applyLog.setPid(applyCommission.getPid());
        applyLog.setPostjson(post);
        applyLog.setUrl(applyCommission.getUrl());
        applyLog.setMsg(applyCommission.getErrmsg());
        applyLog.setErrcode(applyCommission.getErrcode());
        applyLog.setResponsejson(JSON.toJSONString(applyCommission));
        appProductMapper.inserApplyLog(applyLog);
    }


    /**
     * 根据商品找
     * @param request
     */
    public ApplyCommissionResponse applyCommissionByPid(ApplyCommissionRequest request){

        ApplyCommissionResponse response = new  ApplyCommissionResponse();
        if(StringUtils.isEmpty(request.getPid())){
            response.setCode(AppCommon.ERROR);
            response.setMsg("商品ID为空");
            return  response;
        }

        Commission commission = ApplyCommissionUtils.getCommissionForPid(request.getPid());
        if(commission==null){
            response.setCode(AppCommon.ERROR);
            response.setMsg("找不到");
            return  response;
        }

        response.setGoods(commission);
        response.setCode(AppCommon.SUCCESS);

        return  response;
    }

    /**
     * 根据URL找券
     * @param request
     */
    public ApplyCommissionCouponsResponse applyCommissionForCoupons(ApplyCommissionRequest request){
        ApplyCommissionCouponsResponse response = new ApplyCommissionCouponsResponse();
        ApplyCommission commission = ApplyCommissionUtils.get("","",request.getUrl());
        if(commission.getErrcode().equals("0")){
            Commission cm = ApplyCommissionUtils.getCommissionForPid(commission.getPid());
            if(cm!=null){
                ProInfo proInfo = new ProInfo();
                proInfo.setCoupon_click_url(cm.getCommission_coupon());
                proInfo.setCoupon_info(cm.getCoupon_info());
                proInfo.setUrl(cm.getCommission_url());
                proInfo.setPrice(cm.getPrice());
                response.setCode(AppCommon.SUCCESS);
                response.setProInfo(proInfo);
                response.setMsg("成功!");
            }else{
                response.setCode(AppCommon.ERROR);
                response.setMsg("这件商品没有优惠券!");
            }
        }else{
            response.setCode(AppCommon.ERROR);
            response.setMsg("地址解析失败");
        }

        return response;
    }


    public static void main(String[] args) {


     String code ="44CQRUxFRlQgNETooYzotbDpnovlnqvov5Dliqjlh4/pnIfpgI/msJTlkLjmsZfpnovlnqvnlLflpbPoiJLpgILlvpfkuIrnmL7jgJHvvIzlpI3liLbov5nmnaHkv6Hmga/vv6VwcVRjMHVRNTJPTO+/peWQjuaJk+W8gOaJi+a3mA==";
        AppProductService appProductService = new AppProductService();

        SimpleProductResponse simpleProductResponse = appProductService.getComd2(code);

//        String string =  HttpPostGiftCode.QingTaoKe("650723480","561208536564");
         System.out.println(JSON.toJSONString(simpleProductResponse));
    }

}
